const {
  app,
  BrowserWindow,
  dialog // 调用原生对话框的模块
} = require('electron')
const fs = require('fs')
let mainWindow = null
app.on('ready', () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    },
    show: false // 当首次创建窗口的时候，先将它隐藏起来
  })
  mainWindow.webContents.loadFile('./index.html')
  mainWindow.once('ready-to-show', () => {
    mainWindow.show() // DOM 就绪之后展示窗口
    mainWindow.webContents.openDevTools() // 通过代码打开调试窗口
    // getFileFromUser() // 打开选择文件的对话框
  })
  mainWindow.on('closed', () => mainWindow = null)
})

exports.getFileFromUser  = function () {
  const files = dialog.showOpenDialogSync({
    properties: ['openFile'],
    filters: [
      {name: 'Text Files', extensions: ['txt']},
      {name: 'Markdown Files', extensions: ['md', 'markdown']}
    ]
  })
  if (!files) {return}
  const file = files[0]
  const content = fs.readFileSync(file).toString()
  // console.log(content)
  mainWindow.webContents.send('file-opened', file, content)
  
}